package com.template.app.common.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.template.app.common.bean.UploadResult;
import com.template.app.common.service.FileUploadService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;


//import com.contx.cssp.console.dsp.bean.MaterialAddResult;

/**
 * Created by wuxf3 on 2014/5/30.
 */

@Controller
public class FileUploadController {
	private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @Autowired
    private FileUploadService fileUploadService = null;

    private static ObjectMapper mapper=new ObjectMapper();
    
//    @RequestMapping(value="/upload2", method=RequestMethod.POST)
//    @ResponseBody
//    public List<UploadResult> handleMaterialFileUpload(@RequestParam("file") MultipartFile file)
//    		throws Exception{
//    	return fileUploadService.handleFileUpload(file);
//    }
    
//    @RequestMapping(value="/upload/material/banner", method=RequestMethod.POST)
//    @ResponseBody
//    //根据html文本框的文件来上传文件
//    public List<UploadResult> handleBannerMaterialFileUpload(@RequestParam("file") MultipartFile file) throws Exception{
//    	return fileUploadService.handleMaterialFileUpload(file,0);
//    }
//    
//    @RequestMapping(value="/upload/material/wordlink", method=RequestMethod.POST)
//    @ResponseBody
//    //根据html文本框的文件来上传文件
//    public List<UploadResult> handleWordlinkMaterialFileUpload(@RequestParam("file") MultipartFile file) throws Exception{
//    	return fileUploadService.handleMaterialFileUpload(file,2);
//    }
    
    
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public void upload2(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		response.setCharacterEncoding("UTF-8");
		List<UploadResult> result=null;
		logger.info("upload pic work.....");
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		multipartResolver.setMaxUploadSize(2*1024*1024);
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				
				if (file != null) {
					result= fileUploadService.handleFileUpload(file);
				}
				// 记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
				logger.info((finaltime - pre)+"s");
			}

		}else{
			logger.info("文件上传错误");
		}
		if(result!=null && result.size()>0){
			UploadResult r=result.get(0);
			String reason=r.getReason();
			if(!StringUtils.isEmpty(reason)){
				try {
					reason=URLEncoder.encode(reason, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				r.setReason(reason);
			}
			String s=mapper.writeValueAsString(r);
			logger.info(s);
			//return s;
			responseMessage(response,s);
		}
		//return null;
		
	}
	
	
//	@RequestMapping(value="/fileUpload",method=RequestMethod.POST)
//	@ResponseBody
//	public void fileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception{
//		fileUploadService.fileUpload(request,response);
//	}
	
	
	
	
	private void responseMessage(HttpServletResponse response ,String result) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		Writer writer = null;
		try {
			writer = response.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(writer);
		}
	}
}
